package com.bonc.jedis.utils;

import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class JedisExecutor {
	private Jedis jedis;

	public JedisExecutor(Jedis jedis) {
		this.jedis = jedis;
	}
	
	public Jedis getJedis() {
		return this.jedis;
	}
	
	/**
	 * 常用的事务处理模式，如果监听的keys有变化，则循环重新处理
	 * @param transactionHandler
	 * @return
	 */
	public List<Object> transaction(TransactionHandler transactionHandler) {
		try {
			long end = System.currentTimeMillis() +10000;
			while (true) {
				String[] watchs = transactionHandler.getWatchKeys();
				if (watchs!=null && watchs.length > 0) {
					jedis.watch(watchs);
				}
				Transaction trans = jedis.multi();
				List<Object> result = transactionHandler.trans(trans);
				if (result==null) {
					// watch的keys有变化
					continue;
				}else {
					return result;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
